# coding:utf-8
import json

from flask import Flask, jsonify
from flask import make_response
from flask import redirect
from flask import request
from flask import session
from flask import url_for
from werkzeug.routing import BaseConverter, UnicodeConverter
from flask_cors import CORS


class Config(object):
    DEBUG = True

class RegexConverter(BaseConverter):
    def __init__(self,url_map,*args):
        super(RegexConverter, self).__init__(url_map)
        self.regex = args[0]


app = Flask(__name__)

app.secret_key = 'afsafsag'
app.url_map.converters['re'] = RegexConverter
app.url_map.converters['uni'] = UnicodeConverter

# app.config.from_object(Config)
# app.config.from_pyfile('config.ini')
app.config.from_envvar("FLASKCONFIG")


@app.route("/")
def index():
    # a=1/0

    print(app.config.get("DEBUG1", 'azxcv'))

    return "index index"


@app.route("/demo1")
def demo1():
    return "demo1"


@app.route("/user/<user_id>")
def usr_info(user_id):
    return 'user_info %s' % user_id

@app.route("/demo2/<usr_id>",methods=['GET','POST'])
def demo2(usr_id):
    print("demo2"+usr_id)
    return request.method

@app.route('/demo3/<re("[0-9]{3}"):usr_id>')
def demo3(usr_id):
    return "usr_id %s"%usr_id

# @app.route("/pages/<page>")
# @app.route("/demo4/<int:lang_code>")
@app.route("/<string(length=2):lang_code>")
def demo4(lang_code):
    """
    Rule('/pages/<page>'),
    Rule('/<string(length=2):lang_code>')
    :return:
    """
    return "demo4"+lang_code

@app.route("/demo6",methods=["GET","POST"])
def demo6():

    print("*"*50)
    print("请求路径base_url")
    a=request.base_url
    print(a)
    v = request.args.get('a')
    print("请求头:")
    print(request.headers)
    print("请求方法  "+request.method)
    print("请求url  "+request.url)
    print("请求cookies   ")
    print(request.cookies.get('fds'))
    print("请求form表单")
    print(request.form['ss'])

    return 'demo6  '+ v

@app.route('/demo7')
def demo7():
    json_dict = {
        "user_id": 10,
        "user_name": "laowang"
    }
    print(json.dumps(json_dict))
    return jsonify(json_dict)

@app.route("/demo8")
def demo8():
    # return redirect("http://www.baidu.com")
    # return redirect(url_for('index'))
    return redirect(url_for('demo4',lang_code=14))

@app.route("/cookie")
def set_cookie():
    resp = make_response('this is set cookie')
    resp.set_cookie('usrname','afsasaf',max_age=3600)
    return resp

@app.route("/request")
def resp_cookie():
    resp=request.cookies
    print(resp)
    return resp.get('usrname')

@app.route("/set_session")
def set_session():
    session['usrname'] = 'asafa'
    session['pwd'] = 'agsdgsd'
    return 'set session '

@app.route("/get_session")
def get_session():
    return session.get('usrname')

@app.route('/del_session')
def del_session():
    session.pop('usrname','')
    session.pop('pwd','')
    return "del session"


if __name__ == '__main__':
    print(app.url_map)

    app.run()
